<?php
/*
 * @Author: LDY dong2406@126.com
 * @Date: 2022-08-13 08:46:06
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2022-10-29 10:07:39
 */

namespace Ldy\Models;

use Ldy\Model;
use Ldy\Traits\Model\Trees;

class SysDepartment extends Model{

	use Trees;
	
	public $updateWhiteList = ["path"];

    //设置字段名称
    // public $fieldsLabel = [
	// 	"id"=>["comment" =>"ID", "width"=>"80"],
	// 	"desc"=>["width"=>"300"]
	// ];

	// protected $rule = [
	// 	"label"=>"require|min:2",
	// 	"name" => "require|min:2"
	// ];

	// protected $message = [
	// 	"label.min" => "最少不能少于25个字",
	// 	"name.min" => "模块别名不能少于2个字"
	// ];


	public static function getSonDepIds(Int $dep_id, $toString = true){
		$data = self::whereLike('path', "%|{$dep_id}|%")->select();
		$res = [$dep_id];
		if($data->isEmpty()) return $res;
		// $res[] = $dep_id;
		foreach($data as $item) $res[] = $item->id;

		return $toString ? join(',',$res):$res;
	}

	//保存前处理
	public static function onBeforeInsert($model){
		$parent_id = $model->getAttr('parent_id');

		if(!empty($parent_id)){
			$data = $model::where('id', $parent_id)->field('path')->find();
			$parentPath = !$data->isEmpty() ? $data->path:'';
			$path = empty($parentPath) ? "|$parent_id|":$parentPath.$parent_id."|";
			$model->setAttr('path',$path);
		}else{
			$model->setAttr('path','');
		}
	}

	//更新前处理
	public static function onBeforeUpdate($model){
		self::onBeforeInsert($model);
	}

	public static function getOptions($isAll = false){
		if($isAll){
			$data = self::select();
		}else{
			$data = self::where("status", 1)->select();
		}
        
        if($data->isEmpty()) return [];

        $res = [];
        foreach($data->toArray() as $item){
            $res[$item['id']] = $item['name'];
        }

        return $res;
    }

	protected function treesDataWhere($model){
		if(is_root()) return $model;
		$dataAuthDepIds = session('admin.data_auth');
		if(empty($dataAuthDepIds)) return $model;

		if(!is_array($dataAuthDepIds)) $dataAuthDepIds = session('admin.department_id');
		$model = $this->where('id','in', $dataAuthDepIds)->where('status', 1);

		return $model;

	}
    
 }